//简单拓朴排序
class Solution {
public:
    vector<vector<int>> g;
    vector<int> bin;
    vector<int> eventualSafeNodes(vector<vector<int>>& graph) {
        int n = graph.size();
        g.resize(n);
        bin.resize(n,0);

        for(int i = 0;i < n;i++)
        {
            for(int j = 0;j < graph[i].size();j++)
            {
                int next = graph[i][j];
                g[next].push_back(i);
                bin[i]++;
            }
        }

        queue<int> q;
        vector<int> ans;
        for(int i = 0;i < n;i++)
        {
            if(bin[i] == 0)
            {
                q.push(i);
                ans.push_back(i);
            }
        }

        while(!q.empty())
        {
            int cur = q.front();
            q.pop();
            for(int i = 0;i < g[cur].size();i++)
            {
                int next = g[cur][i];
                bin[next]--;
                if(bin[next] == 0)
                {
                    q.push(next);
                    ans.push_back(next);
                }
            }
        }
        ranges::sort(ans);
        return ans;
    }
};